package com.zuowei.ycy.user.okhttps;

import android.widget.Toast;

import com.and.yzy.frame.util.AppManger;
import com.and.yzy.frame.util.Toolkit;
import com.orhanobut.logger.Logger;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by admin on 2016/5/9.
 */
public class HttpUtils {

    public void doCall(String url, RequestParams param, final HttpListener listener, final int what) {
        OkHttpClient okHttpClient = OkHttpUtils.getInstance();
        RequestBody requestBody;
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (int i = 0; i < param.getParams().size(); i++) {
            String key = param.getParams().get(i).getKey();
            Object value = param.getParams().get(i).getValue();
            if (value instanceof File) { //文件
                RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), (File) value);
                builder.addPart(body);
            } else {
                if (Toolkit.isEmpty(key)) {
                    RequestBody body = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), (String) value);
                    builder.addPart(body);
                } else {
                    builder.addPart(Headers.of("Content-Disposition",
                            "form-data; name=\"" + key + "\""),
                            RequestBody.create(null, (String) value));
                }
            }
        }
        requestBody = builder.build();
        final Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Logger.e(e);
                e.printStackTrace();
                listener.onFailure(call, what);
            }

            @Override
            public void onResponse(final Call call, final Response response) {
//                handler.post(new Runnable() {
//                    @Override
//                    public void run() {
                try {
                    String json = response.body().string();
                    Logger.i(json);
                    JSONObject object = new JSONObject(json);
                    if (object.getInt("status") == 200) {
                        try {
                            listener.onSuccess(json, call, response, what);
                        } catch (Exception e) {
                            showToast("网络连接错误");
                            Logger.w("onSuccess中代码有误请检查");
                            Logger.e(e);
                            e.printStackTrace();
                            listener.onParseFail();
                        }
                    } else {
                        try {
                            listener.onError(json, call, response, what);
                        } catch (Exception e) {
                            showToast("网络连接错误");
                            Logger.w("onError中代码有误请检查");
                            Logger.e(e);
                            e.printStackTrace();
                            listener.onParseFail();
                        }
                    }
                } catch (Exception e) {
                    showToast("服务器异常，请重试");
                    listener.onFailure(null, what);
                    e.printStackTrace();
                }
//                    }
//                });
            }

        });
    }

    public Response execute(String url, RequestParams param) {
        OkHttpClient okHttpClient = OkHttpUtils.getInstance();
        RequestBody requestBody;
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (int i = 0; i < param.getParams().size(); i++) {
            String key = param.getParams().get(i).getKey();
            Object value = param.getParams().get(i).getValue();
            if (value instanceof File) { //文件
                RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), (File) value);
                builder.addPart(body);
            } else {
                if (Toolkit.isEmpty(key)) {
                    RequestBody body = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), (String) value);
                    builder.addPart(body);
                } else {
                    builder.addPart(Headers.of("Content-Disposition",
                            "form-data; name=\"" + key + "\""),
                            RequestBody.create(null, (String) value));
                }
            }
        }
        requestBody = builder.build();
        final Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);

        try {
            Response response = call.execute();
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    private void showToast(String message) {
        Toast.makeText(AppManger.getInstance().getTopActivity(), message, Toast.LENGTH_SHORT).show();
    }

}
